package org.maylove.wuziqi.common;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public final class RedisUtil {

    //  设置过期时间（单位：秒）
    private static final Integer EXPIRY_TIME = 60 * 60;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public void set(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
        redisTemplate.expire(key, EXPIRY_TIME, TimeUnit.SECONDS);
    }

    public Object get(String key) {
        redisTemplate.expire(key, EXPIRY_TIME, TimeUnit.SECONDS);
        return redisTemplate.opsForValue().get(key);
    }

    public void delete(String key) {
        redisTemplate.delete(key);
    }

    public boolean exists(String key) {
        redisTemplate.expire(key, EXPIRY_TIME, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(redisTemplate.hasKey(key));
    }

}
